﻿#ifndef __THREADPOOL_H__
#define __THREADPOOL_H__

#include "Thread.h"

namespace sky
{
    // 线程池
    class  ThreadPool
    {
    protected:
        typedef std::vector<Thread *> ThreadList;
        ThreadList mThreads;
        // 当工作线程执行结束后，自动删除
        bool mAutoRemove; 

    public :
        ThreadPool::ThreadPool(void)
        {

        }

        ThreadPool::~ThreadPool(void)
        {
            clear();
        }

        Thread * ThreadPool::add(ThreadRunnable * task, int priority = 0)
        {
            Thread * thread = new Thread();
            if (!thread->spawn(task, priority))
            {
                return NULL;
            }

            mThreads.push_back(thread);

            return thread;
        }

        void ThreadPool::start()
        {
            for(ThreadList::iterator it = mThreads.begin(); it != mThreads.end(); ++it)
            {
                (*it)->start();
            }
        }

        void ThreadPool::pause()
        {
            for(ThreadList::iterator it = mThreads.begin(); it != mThreads.end(); ++it)
            {
                (*it)->pause();
            }
        }

        void ThreadPool::wait()
        {
            for(ThreadList::iterator it = mThreads.begin(); it != mThreads.end(); ++it)
            {
                (*it)->wait();
            }
        }

        void ThreadPool::clear()
        {
            for(ThreadList::iterator it = mThreads.begin(); it != mThreads.end(); ++it)
            {
                delete *it;
            }

            mThreads.clear();
        }

        void ThreadPool::remove(Thread * thread)
        {
            for(ThreadList::iterator it = mThreads.begin(); it != mThreads.end(); ++it)
            {
                if (thread == (*it))
                {
                    delete *it;
                    mThreads.erase(it);

                    return;
                }
            }
        }

        size_t getThreadCount() const {return mThreads.size();}
    };

    
} // namespace sky


#endif